package com.ushine.web.security.handler;

import com.ushine.web.base.model.system.UserDO;
import com.ushine.web.base.facade.IUserRedisFacade;
import com.ushine.web.base.facade.IUserRolePermissionFacade;
import com.ushine.web.security.jwt.JwtProperties;
import com.ushine.web.security.jwt.JwtTokenUtil;
import com.ushine.web.security.redis.RedisTokenClient;
import com.ushine.web.security.response.SecurityResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: yls
 * @Date: 2021/08/15 22:06
 * @Description: 登录成功
 * @Version 1.0
 */
@Slf4j
@Component
public class FightAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private SecurityResponse securityResponse;

    @Resource
    private RedisTokenClient redisTokenClient;

    @Resource
    private IUserRolePermissionFacade userRolePermissionFacade;

    @Resource
    private IUserRedisFacade userRedisFacade;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功，获取认证信息：{}", authentication);
        // 获取登录的用户
        UserDO userDO = (UserDO) authentication.getPrincipal();
        // 生成【token】
        String token = jwtTokenUtil.generateToken(userDO);
        String username = userDO.getUsername();
        // 将【token】放在【redis】中
        redisTokenClient.getUserBucket(username).set(token);
        log.info("登录成功：{}", redisTokenClient.getUserToken(username));
        // 伪装token传给前台
        token = jwtProperties.getPrefix() + token;

        /*
         * 将用户的权限放在redis中
         */
        UserDO user = userRedisFacade.getLoginUserInfo(username);
        user.setToken(token);

        // 登录成功
        securityResponse.getResponse(response, 200, "登录成功！", user);
    }

}
